// #ifdef H5
import {
	saveAs
} from 'file-saver'
// #endif
const global = {
	data() {
		return {
			limit: 20,
			mark: '京瑞居房东模拟数据',
			theme_color: uni.getStorageSync('theme_color') || '#FB2D19',
			my_style: `--color:${uni.getStorageSync('theme_color') || '#FB2D19'};`,
			custom_btn: {
				backgroundColor: uni.getStorageSync('theme_color') || '#FB2D19',
			},
		}
	},
	methods: {
		/**
		 * 跳转
		 * @param {Object} url
		 */
		async jump(url, isLogin) {
		  if (isLogin) {
		    if (!this.isObjNone(this.user)) {
		      this.toLogin(url)
		      return
		    }
		  }
		  uni.navigateTo({
		    url,
		  })
		},
		/**
		 * 返回上一页
		 */
		goBack(number) {
			// #ifndef H5
			uni.navigateBack(number || 1)
			// #endif
			// #ifdef H5
			window.history.back()
			// #endif
		},
		replaceJump(url) {
			uni.redirectTo({
				url,
			})
		},
		reLaunch(url) {
			uni.reLaunch({
				url,
			})
		},
		switchTab(url) {
			uni.switchTab({
				url,
			})
		},
		// 图片预览
		previewImage(item, list) {
			uni.previewImage({
				current: item,
				urls: list,
			})
		},
		/**
		 * 操作成功并返回
		 * @param {Object} msg
		 */
		successBack(msg, num) {
			uni.showToast({
				title: msg,
				icon: 'success',
			})
			setTimeout(() => {
				this.goBack(num)
			}, 1000)
		},
		showMsg(msg, icon) {
			uni.showToast({
				icon: icon || 'none',
				title: msg,
			})
		},
		// 成功
		successGo(info) {
			uni.redirectTo({
				url: `/views/user/success${info}`,
			})
		},
		// 刷新
		refreshList(fn) {
			this.page = 1
			this.list = []
			this.status = 'loading'
			fn && fn()
		},
		// 获取主题色
		// async getThemeColor() {
		//   const res = await this.$api.common.system('getThemeColor')
		//   if (res.code === 200) {
		//     const { color } = res.data
		//     uni.setStorageSync('theme_color', color)
		//   }
		// },
		getThemeColor() {
			this.$api.common.system('getThemeColor').then(res => {
				if (res.code === 200) {
					const {
						color
					} = res.data
					uni.setStorageSync('theme_color', color)
				}
			})
		},
		/**
		 * 获取今天的时间或者指定时间戳
		 * @param date
		 * @returns {string}
		 */
		nowTime(date) {
			return (date ? date / 1000 : new Date().getTime() / 1000).toFixed(0)
		},
		// 去登录
		toLogin() {
			// #ifdef APP-PLUS
			this.reLaunch('/pages/user/login')
			// this.wxLogin()
			// #endif
			// #ifdef H5
			this.reLaunch('/pages/user/login')
			// #endif
			// #ifdef MP-WEIXIN
			this.jump('/pages/auth/authorize')
			// #endif
		},
		// 微信登录
		wxLogin(isBind = true) {
			// #ifdef H5
			// let redirect_uri = window.location.href
			// window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
			// 	'wx99d17d5918a170f6' +
			// 	'&redirect_uri=' + encodeURIComponent(redirect_uri) +
			// 	'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
			uni.showToast({
				icon: 'none',
				title: `请前往APP绑定`,
			})
			this.launchApp()
			// #endif
			// #ifdef APP-PLUS
			let that = this
			// if (!that.is_agree) {
			// 	this.showMsg('请阅读并同意《服务协议》和《隐私政策》')
			// 	return
			// }
			uni.login({
				provider: 'weixin',
				onlyAuthorize: true,
				success(login_res) {
					console.log(login_res)
					if (isBind) {
						that.bindWxappopenAccount(login_res)
					} else {
						that.cancelBindWxappopenAccount(login_res)
					}
				},
				complete() {
					uni.hideLoading()
				},
				fail(e) {
					that.showMsg('登录失败')
				},
			})
			// #endif
		},
		/**
		 * 绑定微信账号APP
		 */
		async bindWxappopenAccount(login_res) {
			let params = {
				appcode: login_res.code,
				nonce: '6666'
			}
			const res = await this.$api.common.user('bindWxappopenAccount', params)
			if (res.code === 200) {
				this.$store.dispatch('getUserInfo').then((res) => {
				})
			}
		},
		/**
		 * 取消绑定微信账号APP
		 */
		async cancelBindWxappopenAccount(login_res) {
			let params = {
				appcode: login_res.code,
				nonce: '6666'
			}
			const res = await this.$api.common.user('cancelBindWxappopenAccount', params)
			console.log(res);
			if (res.code === 200) {
				this.$store.dispatch('getUserInfo').then((res) => {
				})
			}
		},
		toBind() {
			this.jump('/views/auth/bind_phone')
		},
		killTime(end_time) {
			let that = this
			let now_time = (new Date().getTime() / 1000).toFixed(0) // 当前时间
			// 剩余时间
			return +end_time - +now_time
		},
		dataString(date) {
			date = date.substring(0, 19)
			date = date.replace(/-/g, '/') // 必须把日期'-'转为'/'
			return new Date(date).getTime() / 1000
		},

		// 随机字符串
		randomStr(len) {
			len = len || 32
			var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
			var maxPos = chars.length
			var pwd = ''
			for (let i = 0; i < len; i++) {
				pwd += chars.charAt(Math.floor(Math.random() * maxPos))
			}
			return pwd
		},
		isListNone(list) {
			return JSON.stringify(list) !== '[]'
		},
		isObjNone(obj) {
			return JSON.stringify(obj) !== '{}'
		},
		stopClick() {},
		// 复制
		copyText(val) {
			uni.setClipboardData({
				data: val,
				success(res) {
					uni.getClipboardData({
						success(res) {
							uni.showToast({
								title: '复制成功',
							})
						},
					})
				},
			})
		},
		launchApp() {
			let _this = this;
			// #ifdef H5
			let node = document.createElement('a')
			node.href = 'yuanjiequ://'
			node.click()
			// #endif
		},
		h5Copy(content) {
			if (!document.queryCommandSupported('copy')) {
				// 不支持
				return false
			}
			let textarea = document.createElement('textarea')
			textarea.value = content
			textarea.readOnly = 'readOnly'
			document.body.appendChild(textarea)
			textarea.select() // 选择对象
			textarea.setSelectionRange(0, content.length) // 核心
			let result = document.execCommand('copy') // 执行浏览器复制命令
			textarea.remove()
			return result
		},
		// 打电话
		callPhone(phone) {
			uni.makePhoneCall({
				phoneNumber: phone,
			})
		},
		// 数子千分符
		numFormat(num) {
			var res = num.toString().replace(/\d+/, function(n) { // 先提取整数部分
				return n.replace(/(\d)(?=(\d{3})+$)/g, function($1) {
					return $1 + ",";
				});
			})
			return res;
		},
		// 文件下载
		download(url) {
			// #ifdef APP-PLUS
			let dtask = plus.downloader.createDownload(url, {
					//本地路径开头使用file://，跟上手机文件本地目录storage/emulated/0，就是用户文件管理器能看到的了。
					filename: `_downloads/合同.pdf`
				},

				(d, status) => {
					//d为下载的文件对象
					if (status == 200) {

						uni.showToast({
							icon: 'none',
							mask: true,
							title: '文件已保存：' + d.filename, //保存路径
							duration: 3000,
						});
						//下载成功,d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径
						// let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
						// plus.runtime.openFile(d.filename); //选择软件打开文件
					} else {
						//下载失败
						plus.downloader.clear(); //清除下载任务
					}
				})
			dtask.start();
			// #endif
			// #ifndef APP-PLUS
			uni.downloadFile({
				url: url, //下载地址接口返回
				success: (data) => {
					if (data.statusCode === 200) {

						let blod = new Blob([data.tempFilePath], {
							type: 'application/pdf'
						})

						saveAs(data.tempFilePath, '合同.pdf')
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '合同下载成功',
						});
					}
				},
				fail: (err) => {
					uni.showToast({
						icon: 'none',
						mask: true,
						title: '失败请重新下载',
					});
				},
			});
			// #endif
		},
		// 内链外链跳转
		customJump(item) {
			console.log(item)
			const {
				jump_type,
				jump_id
			} = item
			switch (Number(jump_type)) {
				// 自定义页面
				case 1:
					wx.navigateTo({
						url: `/views/home/custom?id=${jump_id}`,
					})
					break
					// 商品
				case 2:
					wx.navigateTo({
						url: `/views/goods/goods_detail?id=${jump_id}`,
					})
					break
					// 领券中心
				case 3:
					wx.navigateTo({
						url: `/views/home/coupon_center`,
					})
					break
					// 满减
				case 4:
					wx.navigateTo({
						url: `/views/home/special?activity_type=manjian&id=${jump_id}`,
					})
					break
					// 限时
				case 5:
					wx.navigateTo({
						url: `/views/home/special?activity_type=discount&id=${jump_id}`,
					})
					break
					// 第二
				case 6:
					wx.navigateTo({
						url: `/views/home/special?activity_type=secondhalf&id=${jump_id}`,
					})
					break
					// 阶梯
				case 7:
					wx.navigateTo({
						url: `/views/home/special?activity_type=jieti&id=${jump_id}`,
					})
					break
				default:
			}
		},
	},
}
export default global
